﻿@using System.Net.Http.Headers;
@using IotClientApp.Shared;
@using IotClientApp.Shared.Enums;
@using Newtonsoft.Json;
@inject HttpClient Http
@inject ISnackbar Snackbar
<MudDialog>
<DialogContent>
    <MudFileUpload T="IBrowserFile" FilesChanged="UploadFiles">
        <ButtonTemplate>
            <MudButton HtmlTag="label"
                       Variant="Variant.Filled"
                       Color="Color.Primary"
                       StartIcon="@Icons.Material.Filled.CloudUpload"
                       for="@context.Id">
                选择文件
            </MudButton>
        </ButtonTemplate>
    </MudFileUpload>    
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="Submit">Ok</MudButton>
    </DialogActions>
</MudDialog>

@code {

    [Parameter]
    public string DeviceId { get; set; }
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }
    private async void Submit()
    {
        if (file == null)
        {
            Snackbar.Add("请选择文件！", Severity.Warning);
            return;
        }
        using var content = new MultipartFormDataContent();
        var fileContent = new StreamContent(file.OpenReadStream(maxFileSize));

        fileContent.Headers.ContentType =
                            new MediaTypeHeaderValue(file.ContentType);
        content.Add(content: fileContent, name: "\"files\"", fileName: file.Name);

        var response = await Http.PostAsync($"/api/Param/UploadFile?deviceId={DeviceId}", content);
        //TODO upload the files to the server
        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            try
            {
                var result = JsonConvert.DeserializeObject<ApiResult<DeviceInfoModel>>(responseContent);
                if (result != null)
                {
                    if (result.Code == ResultCode.Success)
                    {
                        //In a real world scenario this bool would probably be a service to delete the item from api/database
                        Snackbar.Add("导入", Severity.Success);

                        MudDialog.Close(DialogResult.Ok(true));
                    }
                    else
                    {
                        Snackbar.Add(result.ErrorMsg, Severity.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        else
        {
            Snackbar.Add("导入", Severity.Error);
        }
    }
    void Cancel() => MudDialog.Cancel();

    IBrowserFile? file = null;
    long maxFileSize = 1024 * 1024;
    private async void UploadFiles(IBrowserFile file)
    {
        this.file=file;
    }
}
